package com.frame.cfg;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

import com.frame.web.AppErrorController;
import com.mini.core.cfg.MiniConfig;
import com.mini.core.dao.MiniDao;
import com.mini.core.dialect.Dialect;
import com.mini.core.dialect.H2Dialect;
import com.mini.core.dynamic.DynamicDialect;

import net.sf.ehcache.CacheManager;

/**
 * @author sxjun
 * @version 2016-3-11
 */
@Configuration
//@EnableCaching
//@EnableAutoConfiguration
//@EnableWebMvc
public class ApplicationConfiguration {
	private static final Logger log = LoggerFactory.getLogger(ApplicationConfiguration.class);
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private CacheManager cacheManager;
	
	@Autowired
	private ErrorAttributes errorAttributes;

	@Bean
	public AppErrorController appErrorController(){
		 return new AppErrorController(errorAttributes);
	}
	
	/**
	 * 加载H2Dialect方言
	 * @return H2Dialect
	 */
	@Bean
    public Dialect h2Dialect() {
        return new H2Dialect();
    }
	
	/**
	 * 加载动态方言
	 * @return DynamicDialect
	 */
	@Bean
    public DynamicDialect dynamicDialect(){
		DynamicDialect dynamicDialect = new DynamicDialect();
		Map<Object,Dialect> dialect = new HashMap<>();
		dialect.put("h2Dialect", h2Dialect());
		dynamicDialect.setTargetDialect(dialect);
		dynamicDialect.setDefaultDialect(h2Dialect());
		return dynamicDialect;
	}
	
	/**
	 * 配置miniConfig
	 * @return
	 */
	@Bean
	public MiniConfig miniConfig(){
		MiniConfig miniConfig = new MiniConfig();
		miniConfig.setCacheManager(cacheManager);
		miniConfig.setJdbcTemplate(jdbcTemplate);
		miniConfig.setDynamicDialect(dynamicDialect());
		return miniConfig;
	}
	
	/**
	 * 加载MiniDao
	 * @return MiniDao
	 */
	@Bean
	public MiniDao miniDao(){
		MiniDao miniDao = new MiniDao();
		miniDao.setMiniConfig(miniConfig());
		return miniDao;
	}
	
}
